﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.IO.Compression;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using System.Web.Http;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using Google.Protobuf.WellKnownTypes;
using log4net;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.Asn1.Ocsp;
using Org.BouncyCastle.Asn1.X500;
using Org.BouncyCastle.Asn1.X509;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static log4net.Appender.RollingFileAppender;
using CloudApiServer.Services;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;

namespace CloudApiServer.Controllers
{
    /// <summary>
    /// 安徽医保服务控制器
    /// </summary>
    public class FsiApiAnHuiController : ApiController
    {
        private readonly SignInSignOutService _signInSignOuService;
        private readonly FsiPsnInfoService _fsiPsnInfoService;
        private readonly FsiDrugStoreService _fsiDrugStoreService;
        private readonly CatalogQueryService _catalogQueryService;
        private readonly FsiIntegratedQueryService _fsiIntegratedQueryService;
        private readonly YbSettlementStmtService _ybSettlementStmtService;
        private readonly RiskConService _riskConService;
        private readonly FileuploadService _fileuploadService;
        private readonly GoodsService _goodsService;
        private readonly OutpatientDocInfoService _outpatientDocInfoService;
        private readonly FsiReverseService _fsiReverseService;
        public FsiApiAnHuiController()
        {
            _signInSignOuService = new SignInSignOutService();
            _fsiPsnInfoService = new FsiPsnInfoService();
            _fsiDrugStoreService = new FsiDrugStoreService();
            _catalogQueryService = new CatalogQueryService();
            _fsiIntegratedQueryService = new FsiIntegratedQueryService();
            _ybSettlementStmtService = new YbSettlementStmtService();
            _riskConService = new RiskConService();
            _fileuploadService = new FileuploadService();
            _goodsService = new GoodsService();
            _outpatientDocInfoService = new OutpatientDocInfoService();
            _fsiDrugStoreService = new FsiDrugStoreService();
        }
        /*接口*/
        /// <summary>
        /// 医保接口没找到的统一接口返回
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public IHttpActionResult FsiNotFound(HttpRequestMessage request)
        {
            string url = request.RequestUri.ToString();
            string Method = request.Method.ToString();
            string Errnum = LogHelper.GetErrornumber();
            try
            {
                if (string.IsNullOrEmpty(request.Content.ReadAsStringAsync().Result))
                {
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参为空！当前请求入参：" + request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputSignIn>>(request.Content.ReadAsStringAsync().Result);
                    string infno = fsiRequest.infno;
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加！当前请求的接口号：{infno},当前请求入参：" + request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
            }
            catch (JsonReaderException)
            {
                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参格式不正确！服务端无法正常反序列化！请检查入参是否为Json格式！当前请求入参：" + request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);

            }
            catch (Exception ex)
            {
                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且服务端程序处理异常！请联系管理员排查！当前异常提示：{ex.Message},当前请求入参：" + request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);
            }
        }
        /// <summary>
        /// 安徽医保总接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<IHttpActionResult> Fsi_Anhui (HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                string api_name = request.Headers.GetValues("_api_name").FirstOrDefault();
                if (string.IsNullOrEmpty(api_name))
                {
                    throw new Exception($"传入的参数有误!未获取到接口号api_name,请检查请求入参头中是否传入_api_name！");
                }
                var fsiRequestAnHuiHeader = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<object>>>(request.Content.ReadAsStringAsync().Result);
                
                //安徽医保移除校验签到信息
                //if (FsiDatainfo.statesignon == true && api_name != "hsa-fsi-9001" && api_name != "hsa-fsi-9002")
                //{
                //    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequestAnHuiHeader.arg0.fixmedins_code, fsiRequestAnHuiHeader.arg0.opter, fsiRequestAnHuiHeader.arg0.sign_no);
                //    if (sign == false)
                //    {
                //        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                //    }
                //}
                
                if (string.IsNullOrEmpty(api_name))
                {
                    throw new Exception($"传入的参数有误!未获取到接口号api_name,请检查入参！当前入参：{request.Content.ReadAsStringAsync().Result}");
                }
                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                switch (api_name)
                {
                    case "hsa-fsi-9001":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputSignIn>>>(await request.Content.ReadAsStringAsync());
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var signin = await _signInSignOuService.SignInAsync(fsiRequest.arg0, this.GetType().Name);
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = "SUCCESS",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    output = signin,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-9002":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputSignOut>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var siginout = await _signInSignOuService.SignOutAsync(fsiRequest.arg0, this.GetType().Name);
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = "SUCCESS",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    output = siginout,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-1101":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputQueryPsnInfoRequest>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var queryPsnInfo = await _fsiPsnInfoService.QueryPsnInfo(fsiRequest.arg0, this.GetType().Name);
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputQueryPsnInfo>
                            {
                                code = 200,
                                csbCode = 200,
                                message = "SUCCESS",
                                requestId = "",
                                body = new FsiHeader<outputQueryPsnInfo>
                                {
                                    output = queryPsnInfo,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-2101":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var drugstoreSettleAccountsPreA = await _fsiDrugStoreService.DrugstoreSettleAccountsPre(fsiRequest.arg0, this.GetType().Name);
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputDrugstoreSettleAccountsPreA>
                            {
                                code = 200,
                                csbCode = 200,
                                message = "SUCCESS",
                                requestId = "",
                                body = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                                {
                                    output = drugstoreSettleAccountsPreA,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-2102":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var drugstoreSettleAccountsA = await _fsiDrugStoreService.DrugstoreSettleAccounts(fsiRequest.arg0, this.GetType().Name);
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputDrugstoreSettleAccountsPreA>
                            {
                                code = 200,
                                csbCode = 200,
                                message = "SUCCESS",
                                requestId = "",
                                body = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                                {
                                    output = drugstoreSettleAccountsA,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-2103":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputDrugstoreSettleRevokeRequest>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var drugstoreSettleRevoke = await _fsiDrugStoreService.DrugstoreSettleRevoke(fsiRequest.arg0, this.GetType().Name);
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputDrugstoreSettleRevoke>
                            {
                                code = 200,
                                csbCode = 200,
                                message = "SUCCESS",
                                requestId = "",
                                body = new FsiHeader<outputDrugstoreSettleRevoke>
                                {
                                    output = drugstoreSettleRevoke,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-2601":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputRevsMethod>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            bool flag = await _fsiReverseService.RevsMethod(fsiRequest.arg0, this.GetType().Name);
                            if (flag == true)
                            {
                                var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                                {
                                    code = 200,
                                    csbCode = 200,
                                    message = "SUCCESS",
                                    requestId = "",
                                    body = new FsiHeader<outputsignInOut>
                                    {
                                        output = null,
                                        infcode = 0,
                                        warn_msg = null,
                                        cainfo = null,
                                        err_msg = "success",
                                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                        signtype = null,
                                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                    }
                                };
                                return Json(FsiAnHuiHeader);
                            }
                            else
                            {
                                string Errnum = LogHelper.GetErrornumber();
                                var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                                {
                                    code = 200,
                                    csbCode = 200,
                                    message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！调用冲正服务FsiReverseService.RevsMethod返回的状态为{flag}！",
                                    requestId = "",
                                    body = new FsiHeader<outputsignInOut>
                                    {
                                        infcode = -1,
                                        err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！调用冲正服务FsiReverseService.RevsMethod返回的状态为{flag}！"
                                    }
                                };
                                return Json(FsiAnHuiHeader);
                            }
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-3301":
                        try
                        {
                           
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputCatalogCompUp>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            bool flag = await _catalogQueryService.CatalogCompUp(fsiRequest.arg0, this.GetType().Name);
                            if (flag == true)
                            {
                                var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                                {
                                    code = 200,
                                    csbCode = 200,
                                    message = "SUCCESS",
                                    requestId = "",
                                    body = new FsiHeader<outputsignInOut>
                                    {
                                        output = null,
                                        infcode = 0,
                                        warn_msg = null,
                                        cainfo = null,
                                        err_msg = "success",
                                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                        signtype = null,
                                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                    }
                                };
                                return Json(FsiAnHuiHeader);
                            }
                            else
                            {
                                string Errnum = LogHelper.GetErrornumber();
                                var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                                {
                                    code = 200,
                                    csbCode = 200,
                                    message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！调用目录上传服务CatalogQueryService.CatalogCompUp返回的状态为{flag}！",
                                    requestId = "",
                                    body = new FsiHeader<outputsignInOut>
                                    {
                                        infcode = -1,
                                        err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！调用目录上传服务CatalogQueryService.CatalogCompUp返回的状态为{flag}！"
                                    }
                                };
                                return Json(FsiAnHuiHeader);
                            }
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-3302":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputDeleteCatalogCompAudited>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            bool flag = await _catalogQueryService.DeleteCatalogCompAudited(fsiRequest.arg0, this.GetType().Name);
                            if (flag == true)
                            {
                                var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                                {
                                    code = 200,
                                    csbCode = 200,
                                    message = "SUCCESS",
                                    requestId = "",
                                    body = new FsiHeader<outputsignInOut>
                                    {
                                        output = null,
                                        infcode = 0,
                                        warn_msg = null,
                                        cainfo = null,
                                        err_msg = "success",
                                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                        signtype = null,
                                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                    }
                                };
                                return Json(FsiAnHuiHeader);
                            }
                            else
                            {
                                string Errnum = LogHelper.GetErrornumber();
                                var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                                {
                                    code = 200,
                                    csbCode = 200,
                                    message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！调用目录上传服务CatalogQueryService.DeleteCatalogCompAudited返回的状态为{flag}！",
                                    requestId = "",
                                    body = new FsiHeader<outputsignInOut>
                                    {
                                        infcode = -1,
                                        err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！调用目录上传服务CatalogQueryService.DeleteCatalogCompAudited返回的状态为{flag}！"
                                    }
                                };
                                return Json(FsiAnHuiHeader);
                            }
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-1317":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputQueryMedListMapByPageRequest>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            DateTime dateTime = DateTime.Now;
                            Random rnd = new Random();
                            var outputQueryMedListMapByPage = await _catalogQueryService.QueryMedListMapByPage(fsiRequest.arg0, this.GetType().Name);
                            var FsiAnHuiHeader = new FsiAnHuiHeader<OutputQueryMedListMapByPage>
                            {
                                code = 200,
                                csbCode = 200,
                                message = "SUCCESS",
                                requestId = "",
                                body = new FsiHeader<OutputQueryMedListMapByPage>
                                {
                                    output = outputQueryMedListMapByPage,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-3201":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputStmtTotalRequest>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var stmtinfo = await _ybSettlementStmtService.StmtTotal(fsiRequest.arg0, this.GetType().Name);
                            var FsiAnHuiHeader = new FsiAnHuiHeader<OutputStmtTotal>
                            {
                                code = 200,
                                csbCode = 200,
                                message = "SUCCESS",
                                requestId = "",
                                body = new FsiHeader<OutputStmtTotal>
                                {
                                    output = stmtinfo,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-3202":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputStmtDetailRequest>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var fileinfo = await _ybSettlementStmtService.StmtDetail(fsiRequest.arg0, this.GetType().Name);
                            var FsiAnHuiHeader = new FsiAnHuiHeader<OutputStmtDetail>
                            {
                                code = 200,
                                csbCode = 200,
                                message = "SUCCESS",
                                requestId = "",
                                body = new FsiHeader<OutputStmtDetail>
                                {
                                    output = fileinfo,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-5301":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputQueryPsnOpspReg>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var outputQueryPsnOpspReg = await _fsiIntegratedQueryService.QueryPsnOpspReg(fsiRequest.arg0, this.GetType().Name);
                            var FsiAnHuiHeader = new FsiAnHuiHeader<OutputQueryPsnOpspReg>
                            {
                                code = 200,
                                csbCode = 200,
                                message = "SUCCESS",
                                requestId = "",
                                body = new FsiHeader<OutputQueryPsnOpspReg>
                                {
                                    output = outputQueryPsnOpspReg,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    case "hsa-fsi-5206":
                        try
                        {
                            var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputQueryFixmedinsPracPsnSum>>>(request.Content.ReadAsStringAsync().Result);
                            string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            var outputCuminfo = await _fsiIntegratedQueryService.QueryFixmedinsPracPsnSum(fsiRequest.arg0, this.GetType().Name);
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputCuminfo>
                            {
                                code = 200,
                                csbCode = 200,
                                message = "SUCCESS",
                                requestId = "",
                                body = new FsiHeader<outputCuminfo>
                                {
                                    output = outputCuminfo,
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                        catch (Exception ex)
                        {
                            string Errnum = LogHelper.GetErrornumber();
                            var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                            {
                                code = 200,
                                csbCode = 200,
                                message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                requestId = "",
                                body = new FsiHeader<outputsignInOut>
                                {
                                    infcode = -1,
                                    err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                                }
                            };
                            return Json(FsiAnHuiHeader);
                        }
                    default:
                        throw new Exception($"[安徽医保自定义服务]接口号{api_name}未被定义，请检查入参或联系管理员！");
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                {
                    code=200,
                    csbCode = 200,
                    message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                    requestId ="",
                    body = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    }
                };
                return Json(FsiAnHuiHeader);
            }
        }

        /// <summary>
        /// 31013102明细审核事前事中分析服务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<IHttpActionResult> Fsi_Anhui_RiskConServicen(HttpRequestMessage request)
        {
            
            try
            {
               
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                var fsiRequestAnHuiHeader = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputSignIn>>>(request.Content.ReadAsStringAsync().Result);
                string api_name = fsiRequestAnHuiHeader._api_name;
                if (string.IsNullOrEmpty(api_name))
                {
                    throw new Exception($"传入的参数有误!未获取到接口号api_name,请检查入参！当前入参：{request.Content.ReadAsStringAsync().Result}");
                }
                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                switch (api_name)
                {
                    case "hsa-fsi-3101" or "hsa-fsi-3102":
                        using (MySqlConnection conn = new MySqlConnection(connectionString))
                        {
                            try
                            {
                                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestAnHuiHeader<FsiRequestHeader<InputListRiskConServiceresult>>>(request.Content.ReadAsStringAsync().Result);
                                string fsiadmvs = fsiRequest.arg0.mdtrtarea_admvs.Substring(0, 2);
                                string gend = fsiRequest.arg0.Input.data.patient_dtos[0].gend;//性别
                                string patn_id = fsiRequest.arg0.Input.data.patient_dtos[0].patn_id;//人员编号
                                string curr_mdtrt_id = fsiRequest.arg0.Input.data.patient_dtos[0].curr_mdtrt_id;//就诊id

                                List<DatariskConServiceresult> dataList = new List<DatariskConServiceresult>();
                                List<ListRiskConServiceresultFsi_order_dtos> fsi_order_dtos_List = fsiRequest.arg0.Input.data.patient_dtos[0].fsi_encounter_dtos[0].fsi_order_dtos;
                                Random rnd = new Random();
                                DateTime dateTime = DateTime.Now;
                                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);

                                await conn.OpenAsync();
                                using (MySqlCommand cmd = conn.CreateCommand())
                                {
                                    foreach (var item in fsi_order_dtos_List)
                                    {
                                        cmd.CommandText = "select  * from  fsi_riskconserviceproduct where med_list_codg = @med_list_codg ";
                                        cmd.Parameters.AddWithValue("@med_list_codg", item.hilist_code);
                                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                                        {
                                            DataTable dt = new DataTable();
                                            dt.Load(reader);
                                            if (dt.Rows.Count >= 1)
                                            {
                                                for (int i = 0; i < dt.Rows.Count; i++)
                                                {
                                                    List<Judge_result_detail_dtosItem> JudgeresultdetaildtosItem = new List<Judge_result_detail_dtosItem>();
                                                    Judge_result_detail_dtosItem Judge_result_detail_dtosItem = new Judge_result_detail_dtosItem
                                                    {
                                                        vola_item_type = "1",
                                                        mdtrt_id = curr_mdtrt_id,
                                                        jrd_id = Guid.NewGuid().ToString(),
                                                        patn_id = patn_id,
                                                        rx_id = item.rx_id,
                                                        vola_amt = item.sumamt
                                                    };
                                                    JudgeresultdetaildtosItem.Add(Judge_result_detail_dtosItem);
                                                    DatariskConServiceresult riskConServiceresultInfo = new DatariskConServiceresult
                                                    {
                                                        judge_result_detail_dtos = JudgeresultdetaildtosItem,
                                                        rule_id = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}",
                                                        vola_evid = dt.Rows[i]["vola_evid"].ToString(),
                                                        rule_name = dt.Rows[i]["rule_name"].ToString(),
                                                        mdtrt_id = curr_mdtrt_id,
                                                        vola_amt_stas = "1",
                                                        jr_id = Guid.NewGuid().ToString(),
                                                        patn_id = patn_id,
                                                        vola_amt = 1,
                                                        sev_deg = dt.Rows[i]["sev_deg"].ToString(),
                                                        vola_cont = dt.Rows[i]["vola_cont"].ToString(),
                                                        vola_bhvr_type = dt.Rows[i]["vola_bhvr_type"].ToString()
                                                    };
                                                    dataList.Add(riskConServiceresultInfo);
                                                }

                                            }
                                            dt.Dispose();
                                            reader.Close();
                                            reader.Dispose();
                                        }
                                       
                                        cmd.Parameters.Clear();
                                    }
                                }
                                var FsiAnHuiHeader = new FsiAnHuiHeader<OutputriskConService>
                                {
                                    code = 200,
                                    csbCode = 200,
                                    message = "SUCCESS",
                                    requestId = "",
                                    body = new FsiHeader<OutputriskConService>
                                    {
                                        output = new OutputriskConService
                                        {

                                            result = dataList
                                        },
                                        infcode = 0,
                                        warn_msg = null,
                                        cainfo = null,
                                        err_msg = "success",
                                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                        signtype = null,
                                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                        inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                    }
                                };
                                return Json(FsiAnHuiHeader);

                            }
                            catch (Exception ex)
                            {
                                string Errnum = LogHelper.GetErrornumber();
                                var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                                {
                                    code = 200,
                                    csbCode = 200,
                                    message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                                    requestId = "",
                                    body = new FsiHeader<outputsignInOut>
                                    {
                                        infcode = -1,
                                        err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                                    }
                                };
                                return Json(FsiAnHuiHeader);
                            }
                            finally
                            {
                                if (conn.State == ConnectionState.Open)
                                {
                                    await conn.CloseAsync();
                                }
                            }
                        }
                    default:
                        throw new Exception($"[安徽医保自定义接口]接口号{api_name}未被定义，请检查入参或联系管理员！");
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiAnHuiHeader = new FsiAnHuiHeader<outputsignInOut>
                {
                    code = 200,
                    csbCode = 200,
                    message = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                    requestId = "",
                    body = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用安徽医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}" 
                    }
                };
                return Json(FsiAnHuiHeader);
            }
        }
    }
}
